﻿using System;
using Microsoft.SharePoint;
using VPLink2013.Framework;
using VPLink2013.Framework.Extensions;
using VPLink2013.Framework.Constants;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace VPLink2013.Webparts
{
    public class MercureNewsList : WebpartVPLink
    {
        private string strList = "News";

        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected override string GetHtml()
        {
            string strHtml = "";
            ContextTrace.PrefixFileName = "webpart MercureNewsList";

            try
            {
                global = new GlobalVPLink2013();
                global.ListeAnnonces = new List<Annonce>();
                if (!string.IsNullOrEmpty(ParamSharepointSite))
                {
                    Uri paramSiteUri = new Uri(ParamSharepointSite);
                    Uri mercureSiteUri = new Uri(paramSiteUri, "/services/production/Mercure");
                    string strUrl = mercureSiteUri.AbsoluteUri;

                    ContextTrace.AddTrace("strUrl : " + strUrl);

                    string strXslFileName = string.Empty;
                    using (SPSite site = new SPSite(strUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            if (this.Title.StartsWith("Bo"))
                            {
                                strList = "Boîte à idées";
                            }
                            if (this.Title.StartsWith("Coming"))
                            {
                                strList = "Coming next !";
                            }
                            if (this.Title.StartsWith("Le Club"))
                            {
                                strList = "Le Club des 15";
                            }
                            if (this.Title.StartsWith("Présentation"))
                            {
                                strList = "Présentation du programme";
                            }
                            ContextTrace.PrefixFileName = "Mercure - " + strList;

                            ContextTrace.AddTrace("strList : " + strList);


                            string strID = ParamFrm("ItemID");
                            if (string.IsNullOrEmpty(strID))
                            {
                                strID = ParamFrm("ID");
                            }
                            SPList lst = web.Lists.TryGetList(strList);
                            if (string.IsNullOrEmpty(strID))
                            {
                                strXslFileName = "MercureNewsList.xsl";
                                if (lst != null)
                                {
                                    ProcessNewsList(lst);
                                }
                            }
                            else
                            {
                                strXslFileName = "MercureNewsDetail.xsl";
                                if (lst != null)
                                {
                                    ProcessNewsDetail(lst, strID);
                                }
                            }
                        }

                        string strXml = FileSerialization.CreateXmlStringFromObj(global);
                        string strXslPath = Path.Combine(pathVP, "XSL", "NewsVP", strXslFileName);

                        ContextTrace.AddTrace("GetHtml.strXslPath = " + strXslPath);
                        strHtml = GetTransform(strXml, strXslPath);
                    }
                }
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur GetHtml : " + exc.Message + "/" + exc.StackTrace);
            }
            return strHtml;
        }
        #endregion get HTML

        private void ProcessNewsList(SPList lst)
        {
            string strListe = lst.Title;
            SPQuery spQuery = new SPQuery();
            spQuery.RowLimit = 3000;
            StringBuilder sb = new StringBuilder();

            MenuInterneAnnonce mei = new MenuInterneAnnonce();
            //mei.MyTrace = MyTrace;

            global.Filtre = new Filtre();
            global.Filtre.Titre = ParamFrm("FiltreNewsTitre");
            if (global.Filtre.Titre == "Rechercher des news")
            {
                global.Filtre.Titre = "";
            }

            string strDateCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);

            if (strList == "News")
            {
                string strDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
                sb.AppendLine("<Where>");
                sb.AppendLine("         <Leq><FieldRef Name='Date_x0020_publication'/><Value Type='DateTime' IncludeTimeValue='True'>" + strDate + "</Value></Leq>");
                sb.AppendLine("</Where>");
                sb.AppendLine("<OrderBy><FieldRef Name='Date_x0020_publication' Ascending='FALSE'/><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");

                if (string.IsNullOrEmpty(global.Filtre.Titre))
                {
                    global.Filtre.Titre = "Rechercher une news";
                }
                string Query = sb.ToString();
                spQuery.Query = Query;
                ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);
            }


            SPListItemCollection items = lst.GetItems(spQuery);
            ContextTrace.AddTrace("items.Count : " + items.Count.ToString());

            string strPageCrt = ParamFrm("PageCrt");

            int iPageCrt = 1;
            if (!string.IsNullOrEmpty(strPageCrt))
            {
                iPageCrt = int.Parse(strPageCrt);
            }

            global.Filtre.PageCrt = GetControlHidden("PageCrt", iPageCrt.ToString());

            int iPagePrec = 0;
            int iPageSuiv = 0;

            int iNbPerPage = 4;

            int iCrt = 1;
            int iStart = (iPageCrt - 1) * iNbPerPage + 1;
            int iEnd = iPageCrt * iNbPerPage;

            ContextTrace.AddTrace("iStart : " + iStart.ToString());
            ContextTrace.AddTrace("iEnd : " + iEnd.ToString());

            foreach (SPListItem item in items)
            {
                ContextTrace.AddTrace("iCrt : " + iCrt.ToString());
                if (iCrt < iStart)
                {
                    iPagePrec = iPageCrt - 1;
                    ContextTrace.AddTrace("iPagePrec : " + iPagePrec.ToString());
                }
                if (iCrt > iEnd)
                {
                    iPageSuiv = iPageCrt + 1;
                    ContextTrace.AddTrace("iPageSuiv : " + iPageSuiv.ToString());
                }
                if (iCrt >= iStart && iCrt <= iEnd)
                {
                    ContextTrace.AddTrace("-------------------------------");

                    Annonce ann = new Annonce();
                    ann.ID = item.ID.ToString();
                    ann.LinkDetail = ParamSharepointSite + "/services/production/Mercure/Pages/NewsDetail.aspx?ItemID=" + ann.ID;
                    if (strList == "News")
                    {
                        ann.DatePublication = item.GetItemListFieldValueAsDateTime(Fields.DatePublicationField);
                    }
                    if (strList == "Le Club des 15" || strList == "Présentation du programme")
                    {
                        ann.URL = item.GetItemListFieldValueAsUrlValue(Fields.UrlNewsField);
                    }
                    else
                    {
                        ann.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
                        ann.TitrePiwik = ann.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
                        ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.DescriptionField);
                        ann.Attachments = FormatDetailAttachments(item, false);
                    }
                    ann.Photo1 = item.GetItemListFieldValueAsUrlValue(Fields.PhotoField);

                    ContextTrace.AddTrace("ann.ID : " + ann.ID);
                    ContextTrace.AddTrace("ann.Titre : " + ann.Titre);
                    ContextTrace.AddTrace("ann.Chapeau : " + ann.Chapeau);
                    ContextTrace.AddTrace("ann.Photo1 : " + ann.Photo1);

                    global.ListeAnnonces.Add(ann);
                }
                iCrt += 1;
            }
            #region paging
            if (iPagePrec > 0 || iPageSuiv > 0)
            {
                StringBuilder sbNavigationPages = new StringBuilder();
                sbNavigationPages.AppendLine("<div>");

                if (iPagePrec > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPagePrec.ToString() + ");\">");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/VentePrivee2013/Images/pages_news_left.jpg\" width=\"6\" height=\"11\" border='0'>");
                    sbNavigationPages.AppendLine("   Page précédente");
                    sbNavigationPages.AppendLine("</a>");
                }
                if (iPagePrec > 0 && iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<span>|</span>");
                }
                if (iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPageSuiv.ToString() + ");\">");
                    sbNavigationPages.AppendLine("Page suivante   ");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/VentePrivee2013/Images/pages_news_right.jpg\" width=\"6\" height=\"11\" border='0'>");
                    sbNavigationPages.AppendLine("</a>");
                }
                sbNavigationPages.AppendLine("</div>");

                global.Filtre.NavigationPages = sbNavigationPages.ToString();
                global.Filtre.NavigationPagesBottom = sbNavigationPages.ToString();

                ContextTrace.AddTrace("global.Filtre.NavigationPages : " + global.Filtre.NavigationPages);
            }
            #endregion
        }

        private void ProcessNewsDetail(SPList lst, string strID)
        {
            try
            {
                int idChantier = int.Parse(strID);
                SPListItem item = lst.Items.GetItemById(idChantier);

                Annonce ann = new Annonce();
                ann.ID = item.ID.ToString();
                ann.LinkDetail = ParamSharepointSite + "/services/production/Mercure/Pages/default.aspx";

                if (strList == "Le Club des 15" || strList == "Présentation du programme")
                {
                    ann.URL = item.GetItemListFieldValueAsUrlValue(Fields.UrlNewsField);
                }
                else
                {
                    ann.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
                    ann.TitrePiwik = ann.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
                    ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.DescriptionField);
                    ann.DatePublication = item.GetItemListFieldValueAsDateTime(Fields.DatePublicationField);
                    ann.Attachments = FormatDetailAttachments(item, false);
                }

                ann.Photo1 = item.GetItemListFieldValueAsUrlValue(Fields.PhotoField);
                ann.Attachments = FormatDetailAttachments(item, false);

                ContextTrace.AddTrace("ann.ID : " + ann.ID);
                ContextTrace.AddTrace("ann.Titre : " + ann.Titre);
                ContextTrace.AddTrace("ann.Chapeau : " + ann.Chapeau);

                global.ListeAnnonces.Add(ann);
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Error.ProcessChantierDetail : " + exc.Message + "/" + exc.StackTrace);
            }
        }
    }
}
